package ravenmocker.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Properties;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

public class Generator {
	
	public String parse(String template, IComponent component) {
		Properties properties = new Properties();
		try {
			InputStream config = new FileInputStream(new File("ravenmocker.properties"));
			properties.load(config);
		} catch (IOException e1) { e1.printStackTrace(); }
		
		VelocityContext context = new VelocityContext();
		context.put("builder", new String());
		context.put("basepath", properties.getProperty("base-path"));
		if (component instanceof Table)
			context.put("component", (Table)component);
		context.put("generator", new Generator());
		
		StringWriter writer = new StringWriter();
		try {
			Velocity.mergeTemplate(template, "UTF-8", context, writer);
		} catch (ResourceNotFoundException e) { e.printStackTrace();
		} catch (ParseErrorException e) { e.printStackTrace();
		} catch (MethodInvocationException e) { e.printStackTrace();
		} catch (Exception e) { e.printStackTrace(); }
		return writer.toString();
	}
	
}
